﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MAT.Model;
using System.Windows.Forms;
using Microsoft.Win32;
using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace MAT.Controllers
{
    class ctrNotice
    {
        public static frmNotice _frmNotice = null;

        public frmNotice FrmNotice
        {
            get { return _frmNotice; }
            set { _frmNotice = value; }
        }

        ////Implement one object to set statup application
        public static int reqID;
        public static string emp_ID;
        public static int row;
        public static string _control = null;
        MAT_Context context = MATContext.getContext();
        static List<REQUEST_NEW> req_new = new List<REQUEST_NEW>();
        static List<REQUEST_LIQUIDATION> req_liq = new List<REQUEST_LIQUIDATION>();
        static List<REQUEST_MAINTENANCE> req_mai = new List<REQUEST_MAINTENANCE>();
        static List<REQUEST_BORROW> req_bor = new List<REQUEST_BORROW>();
        List<REQUEST_NEW> nTemps = new List<REQUEST_NEW>();
        List<REQUEST_LIQUIDATION> lTemps = new List<REQUEST_LIQUIDATION>();
        List<REQUEST_MAINTENANCE> mTemps = new List<REQUEST_MAINTENANCE>();
        List<REQUEST_BORROW> bTemps = new List<REQUEST_BORROW>();

        //Load data into columns in datagridview
        private void initial()
        {
            _frmNotice.Date.DataPropertyName = "REQUEST_DATE";
            for (int i = 0; i < _frmNotice.dataGridViewRequest.RowCount; i++)
            {
                try
                {
                    //Load data from Employee ID column in datagridview (it is invisible)
                    emp_ID = _frmNotice.dataGridViewRequest.Rows[i].Cells[5].Value.ToString();
                    _frmNotice.dataGridViewRequest.Rows[i].Cells[1].Value = context.OWNERS.FirstOrDefault(o => o.EMPLOYEE_ID == emp_ID).EMPLOYEE_NAME;

                    //Load Category data when user choose Request New
                    if (split(_frmNotice.listBoxRequest.SelectedItem.ToString()) == "request new")
                    {
                        emp_ID = _frmNotice.dataGridViewRequest.Rows[i].Cells[6].Value.ToString();
                        _frmNotice.dataGridViewRequest.Rows[i].Cells[2].Value = context.CATEGORies.FirstOrDefault(ca => ca.CATEGORY_ID == emp_ID).CATEGORY_NAME;
                    }
                    //Load data from Asset ID column in datagridview (it is invisible)
                    else
                    {
                        emp_ID = _frmNotice.dataGridViewRequest.Rows[i].Cells[6].Value.ToString();
                        _frmNotice.dataGridViewRequest.Rows[i].Cells[2].Value = context.ASSETs.FirstOrDefault(ass => ass.ASSET_ID == emp_ID).ASSET_NAME;
                    }
                }
                catch { }
            }
        }

        //Load data belong to Admin 0 and Admin 1
        private void load_request_belong(string input)
        {
            try
            {
                foreach (REQUEST_NEW reN in context.REQUEST_NEW.Where(rN => rN.REQ_STATUS == input).ToList())
                    if (!req_new.Contains(reN))
                        req_new.Add(reN);
                foreach (REQUEST_LIQUIDATION reL in context.REQUEST_LIQUIDATION.Where(rL => rL.REQ_STATUS == input).ToList())
                    if (!req_liq.Contains(reL))
                        req_liq.Add(reL);
                foreach (REQUEST_MAINTENANCE reM in context.REQUEST_MAINTENANCE.Where(rM => rM.REQ_STATUS == input).ToList())
                    if (!req_mai.Contains(reM))
                        req_mai.Add(reM);
                foreach (REQUEST_BORROW reB in context.REQUEST_BORROW.Where(rB => rB.REQ_STATUS == input).ToList())
                    if (!req_bor.Contains(reB))
                        req_bor.Add(reB);
            }
            catch { }
        }

        //Get the name of Request
        private string split(string a)
        {
            int index = a.IndexOf('(');
            string result = a.Substring(0, index - 1);
            return result.ToLower();
        }

        //Clear all data in the form
        private void clearData()
        {
            _frmNotice.dataGridViewRequest.DataSource = null;
            _frmNotice.txtAsset.Text = "";
            _frmNotice.txtEmployee.Text = "";
            _frmNotice.txtReason.Text = "";
            _frmNotice.txtRequestDate.Text = "";
            _frmNotice.txtRequestID.Text = "";
            _frmNotice.lblDisposal.Visible = false;
            _frmNotice.txtDisposal.Visible = false;
            _frmNotice.txtDisposal.Text = "";
        }

        //Load data for Notice form/
        private void load_data()
        {
            req_new.Clear();
            req_liq.Clear();
            req_mai.Clear();
            req_bor.Clear();
            //
            //Load all requests belong to User logged into the system
            //
            try
            {
                string temp = MAT.Controllers.ctrLogin.employee_ID;
                foreach (REQUEST_NEW reN in context.REQUEST_NEW.Where(rN => rN.EMPLOYEE_ID == temp).ToList())
                    req_new.Add(reN);
                foreach (REQUEST_LIQUIDATION reL in context.REQUEST_LIQUIDATION.Where(rL => rL.EMPLOYEE_ID == temp).ToList())
                    req_liq.Add(reL);
                foreach (REQUEST_MAINTENANCE reM in context.REQUEST_MAINTENANCE.Where(rM => rM.EMPLOYEE_ID == temp).ToList())
                    req_mai.Add(reM);
                foreach (REQUEST_BORROW reB in context.REQUEST_BORROW.Where(rB => rB.EMPLOYEE_ID == temp).ToList())
                    req_bor.Add(reB);
            }
            catch { }
            ////For Admin_2
            ////Load all requests were requested by User
            if (MAT.Controllers.ctrLogin.priority == 2)
            {
                nTemps.Clear();
                lTemps.Clear();
                mTemps.Clear();
                bTemps.Clear();
                try
                {
                    string emID = MAT.Controllers.ctrLogin.employee_ID;
                    List<OWNER> owners = context.OWNERS.Where(o => o.MANAGE == emID).ToList();
                    //List all assets is requested by owner in the Owner list
                    foreach (OWNER own in owners)
                    {
                        foreach (REQUEST_NEW nTemp in context.REQUEST_NEW.Where(nT => nT.EMPLOYEE_ID == own.EMPLOYEE_ID).ToList())
                            nTemps.Add(nTemp);
                        foreach (REQUEST_LIQUIDATION lTemp in context.REQUEST_LIQUIDATION.Where(lT => lT.EMPLOYEE_ID == own.EMPLOYEE_ID).ToList())
                            lTemps.Add(lTemp);
                        foreach (REQUEST_MAINTENANCE mTemp in context.REQUEST_MAINTENANCE.Where(mT => mT.EMPLOYEE_ID == own.EMPLOYEE_ID).ToList())
                            mTemps.Add(mTemp);
                        foreach (REQUEST_BORROW bTemp in context.REQUEST_BORROW.Where(bT => bT.EMPLOYEE_ID == own.EMPLOYEE_ID).ToList())
                            bTemps.Add(bTemp);
                    }

                    foreach (REQUEST_NEW reN in nTemps.Where(nTs => nTs.REQ_STATUS == "RE001").ToList())
                        if (!req_new.Contains(reN))
                            req_new.Add(reN);
                    foreach (REQUEST_LIQUIDATION reL in lTemps.Where(lTs => lTs.REQ_STATUS == "RE001").ToList())
                        if (!req_liq.Contains(reL))
                            req_liq.Add(reL);
                    foreach (REQUEST_MAINTENANCE reM in mTemps.Where(mTs => mTs.REQ_STATUS == "RE001").ToList())
                        if (!req_mai.Contains(reM))
                            req_mai.Add(reM);
                    foreach (REQUEST_BORROW reB in bTemps.Where(bTs => bTs.REQ_STATUS == "RE001").ToList())
                        if (!req_bor.Contains(reB))
                            req_bor.Add(reB);
                }
                catch { }
            }

            switch (MAT.Controllers.ctrLogin.priority)
            {
                //For Admin_0
                //Load all requests were approved by Admin_2
                case 0: load_request_belong("RE003"); break;

                //For Admin_1
                //Load all requests were approved by Admin_0
                case 1: load_request_belong("RE004"); break;
            }
        }

        private string split_request(int _newFile, int _liquidationFile, int _maintenanceFile, int _borrowFile)
        {
            if (!File.Exists(Application.StartupPath + @"\Request.txt"))
                File.Create(Application.StartupPath + @"\Request.txt");
            StreamReader readFile = new StreamReader(Application.StartupPath + @"\Request.txt");
            string str = readFile.ReadLine();
            readFile.Close();

            //Split the string to select requests of user logged into MAT system
            int count = 0;
            char[] A = str.ToCharArray();
            int start = str.IndexOf(MAT.Controllers.ctrLogin.employee_ID);
            do
            {
                count++;
                start++;
            } while (A[start] != ' ');
            str = str.Substring(str.IndexOf(MAT.Controllers.ctrLogin.employee_ID), count);

            int firstBrace = str.IndexOf("(");
            int first = str.IndexOf('_');
            int second = str.IndexOf('|');
            int third = str.IndexOf('-');
            int _new = Convert.ToInt16(str.Substring(firstBrace + 1, first - firstBrace - 1));
            int _liq = Convert.ToInt16(str.Substring(first + 1, second - first - 1));
            int _mai = Convert.ToInt16(str.Substring(second + 1, third - second - 1));
            int _bor = Convert.ToInt16(str.Substring(third + 1, str.Length - 2 - third));

            string message = null;

            if (_bor < _borrowFile)
            {
                message += _borrowFile - _bor + " new Request Asset Borrow ";
            }
            if (_liq < _liquidationFile)
            {
                message += _liquidationFile - _liq + " new Request Asset Liquidation ";
            }
            if (_mai < _maintenanceFile)
            {
                message += _maintenanceFile - _mai + " new Request Asset Maintenance ";
            }
            if (_new < _newFile)
            {
                message += _newFile - _new + " new Request New Asset ";
            }
            return message;
        }

        //Action for Show Notice function
        public void showNoticeToolStripMenuItem_Click()
        {
            if (_frmNotice == null)
                _frmNotice = new frmNotice();
            _frmNotice.Show();
            _frmNotice.Focus();
            btnReload_Click();
            _frmNotice.timerLoad.Stop();
        }

        //Action for Show Main Form function
        public void matCentralMainForm_Click()
        {
            MAT.Controllers.ctrMain._frmMain.Show();
        }

        //Action for Show About Message functin
        public void aboutJupiter_Click()
        {
            MessageBox.Show("Mobile Asset Tracking - MAT \n"
                            + "Jupiter Team \n\n"
                            + "PHAM T.L. Trinh \n"
                            + "HO T. Duc \n"
                            + "NGUYEN H. Phuc \n"
                            + "NGUYEN T. Anh \n"
                            + "NGUYEN T.H. Thanh");
        }

        public void signOutToolStripMenuItem_Click()
        {
            if (MessageBox.Show("Do you really want to sign out?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    //Set flag for user (logged in)
                    LOG_IN login = context.LOG_IN.FirstOrDefault(log => log.USERNAME == MAT.Controllers.ctrLogin.Username);
                    login.LOGGED = 0;
                    context.SaveChanges();
                }
                catch { }

                _frmNotice.Dispose();
                frmLogin f = new frmLogin();
                f.ShowDialog();
                f.Focus();
            }
        }

        //Action for Exit function
        public void exitToolStripMenuItem_Click()
        {
            if (MessageBox.Show("Do you want to exit the application?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                context.LOG_IN.FirstOrDefault(log => log.USERNAME == MAT.Controllers.ctrLogin.Username).LOGGED = 0;
                context.SaveChanges();
                Application.Exit();
            }
        }

        //Load data from database to write into Request.txt file (using for ctrLoad, ctrLogin, ctrNotice)
        public void load_check_data()
        {
            load_data();

            //Check EmployeeID in Request.txt
            if (!File.Exists(Application.StartupPath + @"\Request.txt"))
                File.Create(Application.StartupPath + @"\Request.txt");
            StreamReader readFile = new StreamReader(Application.StartupPath + @"\Request.txt");
            string output = readFile.ReadLine();
            readFile.Close();
            if (output == null || !output.Contains(MAT.Controllers.ctrLogin.employee_ID))
            {
                _frmNotice.timerLoad.Stop();
                //Save status of request in Request.txt file
                StreamWriter ghi = new StreamWriter(Application.StartupPath + @"\Request.txt");
                ghi.Flush();
                string textWrite = MAT.Controllers.ctrLogin.employee_ID + "(" + req_new.Count + "_" + req_liq.Count + "|" + req_mai.Count + "-" + req_bor.Count + ") ";
                if (output == null)
                    ghi.Write(textWrite);
                //Write more data
                if (output != null)
                    ghi.Write(output + textWrite);
                ghi.Close();
                _frmNotice.timerLoad.Start();
            }
            else
            {
                _frmNotice.timerLoad.Stop();
                StreamReader _readFile = new StreamReader(Application.StartupPath + @"\Request.txt");
                string str = _readFile.ReadLine();
                _readFile.Close();

                //Split the string to select requests of user logged into MAT system
                int count = 0;
                char[] A = str.ToCharArray();
                int start = str.IndexOf(MAT.Controllers.ctrLogin.employee_ID);
                do
                {
                    count++;
                    start++;
                } while (A[start] != ' ');
                string _new = MAT.Controllers.ctrLogin.employee_ID + "(" + req_new.Count + "_" + req_liq.Count + "|" + req_mai.Count + "-" + req_bor.Count + ")";
                str = str.Replace(str.Substring(str.IndexOf(MAT.Controllers.ctrLogin.employee_ID), count), _new);
                StreamWriter ghi = new StreamWriter(Application.StartupPath + @"\Request.txt");
                ghi.Flush();
                ghi.Write(str);
                ghi.Close();
                _frmNotice.timerLoad.Start();
            }
        }

        private void write_XML(string type, string REQ_ID, string asset_name, string request_date, string sender, string reason, string return_date)
        {
            XElement MAT = new XElement(type.ToUpper());
            if (MAT.Name != "MAINTENANCE")
                MAT.Add(new XElement("Request_ID", REQ_ID), 
                        new XElement("Asset_Name", asset_name), 
                        new XElement("Request_date", request_date), 
                        new XElement("Employee", sender), 
                        new XElement("Reason", reason));
            if (MAT.Name == "MAINTENANCE")
                MAT.Add(new XElement("Request_ID", REQ_ID),
                        new XElement("Asset_Name", asset_name),
                        new XElement("Request_date", request_date),
                        new XElement("Employee", sender),
                        new XElement("Reason", reason), 
                        new XElement("Return_Date", return_date));
            var doc = new XDocument();
            //create xml file.
            if (File.Exists(Application.StartupPath + @"\..\..\XML\" + type + ".xml"))
            {
                doc = XDocument.Load(Application.StartupPath + @"\..\..\XML\" + type + ".xml");
                doc.Element("MAT").Add(MAT);//grandfather node (MAT)
            }
            else
            {
                doc = new XDocument(new XElement("MAT", MAT));
            }
            doc.Save(Application.StartupPath + @"\..\..\XML\" + type + ".xml");
        }

        public void frmNotice_Load()
        {
            //Write to Form's title
            _frmNotice.Text = "Notice Form - " + context.OWNERS.FirstOrDefault(o => o.EMPLOYEE_ID == MAT.Controllers.ctrLogin.employee_ID).EMPLOYEE_NAME;
            clearData();
            _frmNotice.btnOK.Enabled = false;
            _frmNotice.listBoxRequest.Enabled = true;
            _frmNotice.dataGridViewRequest.Enabled = false;
            _frmNotice.dataGridViewRequest.AutoGenerateColumns = false;
            _frmNotice.listBoxRequest.Items.Clear();
            load_check_data();

            //Count the asset to view in the notice
            _frmNotice.listBoxRequest.Items.Add("Request New (" + req_new.Count + ")");
            _frmNotice.listBoxRequest.Items.Add("Request Liquidation (" + req_liq.Count + ")");
            _frmNotice.listBoxRequest.Items.Add("Request Maintenance (" + req_mai.Count + ")");
            _frmNotice.listBoxRequest.Items.Add("Request Borrow (" + req_bor.Count + ")");

            //Stop timer to execute
            _frmNotice.timerLoad.Stop();
        }

        //Action when user choose one of objects in the listBox
        public void listBoxRequest_SelectedIndexChanged()
        {
            clearData();
            _frmNotice.dataGridViewRequest.Enabled = true;
            string input = split(_frmNotice.listBoxRequest.SelectedItem.ToString());
            if (input == "request new")
            {
                _frmNotice.AssetID.DataPropertyName = "CATEGORY_ID";
                _frmNotice.dataGridViewRequest.DataSource = req_new;
                initial();
            }
            else
            {
                _frmNotice.AssetID.DataPropertyName = "ASSET_ID";
                if (input == "request liquidation")
                {
                    _frmNotice.dataGridViewRequest.DataSource = req_liq;
                }
                else
                    if (input == "request maintenance")
                    {
                        _frmNotice.dataGridViewRequest.DataSource = req_mai;
                    }
                    else
                    {
                        _frmNotice.dataGridViewRequest.DataSource = req_bor;
                    }
                initial();
            }
        }

        //Action when user click on one of rows in the datagridview
        public void dataGridViewRequest_CellClick()
        {
            row = _frmNotice.dataGridViewRequest.SelectedCells[0].RowIndex;
            if (((DataGridViewComboBoxCell)_frmNotice.dataGridViewRequest.Rows[row].Cells[0]).Value != null)
            {
                _frmNotice.btnOK.Enabled = true;
                _frmNotice.listBoxRequest.Enabled = false;
            }
            //
            //Get Request_ID in datagridview (it is invisible)
            //
            reqID = Convert.ToInt16(_frmNotice.dataGridViewRequest.Rows[row].Cells[4].Value);
            string input = split(_frmNotice.listBoxRequest.SelectedItem.ToString());
            if (input == "request new")
            {
                REQUEST_NEW rN = context.REQUEST_NEW.FirstOrDefault(re => re.REQUEST_ID == reqID);
                context.Refresh(System.Data.Objects.RefreshMode.ClientWins, rN);
                _frmNotice.txtRequestID.Text = reqID.ToString();
                _frmNotice.txtEmployee.Text = _frmNotice.dataGridViewRequest.Rows[row].Cells[1].Value.ToString();
                _frmNotice.txtAsset.Text = _frmNotice.dataGridViewRequest.Rows[row].Cells[2].Value.ToString();
                _frmNotice.txtRequestDate.Text = rN.REQUEST_DATE.ToString();
                _frmNotice.txtReason.Text = rN.REASON;

                _frmNotice.lblDisposal.Visible = false;
                _frmNotice.txtDisposal.Visible = false;

                //Load choices for Status combobox
                CommonClassExecute<REQUEST_NEW> cce = new CommonClassExecute<REQUEST_NEW>(rN.REQ_STATUS);
                cce.display_combobox(row, _frmNotice.dataGridViewRequest, MAT.Controllers.ctrLogin.priority, MAT.Controllers.ctrLogin.employee_ID);
            }
            else
                if (input == "request liquidation")
                {
                    REQUEST_LIQUIDATION rL = context.REQUEST_LIQUIDATION.FirstOrDefault(re => re.REQUEST_ID == reqID);
                    context.Refresh(System.Data.Objects.RefreshMode.ClientWins, rL);
                    _frmNotice.txtRequestID.Text = reqID.ToString();
                    _frmNotice.txtEmployee.Text = _frmNotice.dataGridViewRequest.Rows[row].Cells[1].Value.ToString();
                    _frmNotice.txtAsset.Text = _frmNotice.dataGridViewRequest.Rows[row].Cells[2].Value.ToString();
                    _frmNotice.txtRequestDate.Text = rL.REQUEST_DATE.ToString();
                    _frmNotice.txtReason.Text = rL.REASON;

                    _frmNotice.lblDisposal.Visible = true;
                    _frmNotice.txtDisposal.Visible = true;
                    _frmNotice.txtDisposal.Text = rL.DISPOSAL_REQ;

                    //Load choices for Status combobox
                    CommonClassExecute<REQUEST_LIQUIDATION> cce = new CommonClassExecute<REQUEST_LIQUIDATION>(rL.REQ_STATUS);
                    cce.display_combobox(row, _frmNotice.dataGridViewRequest, MAT.Controllers.ctrLogin.priority, MAT.Controllers.ctrLogin.employee_ID);
                }
                else
                    if (input == "request maintenance")
                    {
                        REQUEST_MAINTENANCE rM = context.REQUEST_MAINTENANCE.FirstOrDefault(re => re.REQUEST_ID == reqID);
                        context.Refresh(System.Data.Objects.RefreshMode.ClientWins, rM);
                        _frmNotice.txtRequestID.Text = reqID.ToString();
                        _frmNotice.txtEmployee.Text = _frmNotice.dataGridViewRequest.Rows[row].Cells[1].Value.ToString();
                        _frmNotice.txtAsset.Text = _frmNotice.dataGridViewRequest.Rows[row].Cells[2].Value.ToString();
                        _frmNotice.txtRequestDate.Text = rM.STARTS_DATE.ToString();
                        _frmNotice.txtReason.Text = rM.REASON;

                        _frmNotice.lblDisposal.Visible = false;
                        _frmNotice.txtDisposal.Visible = false;

                        //Load choices for Status combobox
                        CommonClassExecute<REQUEST_MAINTENANCE> cce = new CommonClassExecute<REQUEST_MAINTENANCE>(rM.REQ_STATUS);
                        cce.display_combobox(row, _frmNotice.dataGridViewRequest, MAT.Controllers.ctrLogin.priority, MAT.Controllers.ctrLogin.employee_ID);
                    }
                    else
                    {
                        REQUEST_BORROW rB = context.REQUEST_BORROW.FirstOrDefault(re => re.REQUEST_ID == reqID);
                        context.Refresh(System.Data.Objects.RefreshMode.ClientWins, rB);
                        _frmNotice.txtRequestID.Text = reqID.ToString();
                        _frmNotice.txtEmployee.Text = _frmNotice.dataGridViewRequest.Rows[row].Cells[1].Value.ToString();
                        _frmNotice.txtAsset.Text = _frmNotice.dataGridViewRequest.Rows[row].Cells[2].Value.ToString();
                        _frmNotice.txtRequestDate.Text = rB.REQUEST_DATE.ToString();
                        _frmNotice.txtReason.Text = rB.REASON;

                        _frmNotice.lblDisposal.Visible = false;
                        _frmNotice.txtDisposal.Visible = false;

                        //Load choices for Status combobox
                        CommonClassExecute<REQUEST_BORROW> cce = new CommonClassExecute<REQUEST_BORROW>(rB.REQ_STATUS);
                        cce.display_combobox(row, _frmNotice.dataGridViewRequest, MAT.Controllers.ctrLogin.priority, MAT.Controllers.ctrLogin.employee_ID);
                    }
        }

        public void btnReload_Click()
        {
            frmNotice_Load();
        }

        public void btnOK_Click()
        {
            _frmNotice.btnOK.Enabled = false;
            _frmNotice.listBoxRequest.Enabled = true;
            if (_frmNotice.dataGridViewRequest.DataSource != null)
            {
                for (int i = 0; i < _frmNotice.dataGridViewRequest.RowCount; i++)
                {
                    if (((DataGridViewComboBoxCell)_frmNotice.dataGridViewRequest.Rows[i].Cells[0]).Value != null)
                    {
                        string result = ((DataGridViewComboBoxCell)_frmNotice.dataGridViewRequest.Rows[i].Cells[0]).Value.ToString();
                        int requestID = Convert.ToInt16(_frmNotice.dataGridViewRequest.Rows[i].Cells[4].Value);
                        string input = split(_frmNotice.listBoxRequest.SelectedItem.ToString());
                        if (input == "request new")
                        {
                            REQUEST_NEW rN = context.REQUEST_NEW.FirstOrDefault(r => r.REQUEST_ID == requestID);
                            CommonClassExecute<REQUEST_NEW> cce = new CommonClassExecute<REQUEST_NEW>(rN.REQ_STATUS);
                            rN.REQ_STATUS = cce.execute_request(result);
                            if (_control == "Delete")
                            {
                                context.DeleteObject(rN);
                                _control = null;
                            }
                            if (rN.REQ_STATUS == "RE006")
                            {
                                string category_id = context.REQUEST_NEW.FirstOrDefault(ne => ne.REQUEST_ID == requestID).CATEGORY_ID;
                                string category_name = context.CATEGORies.FirstOrDefault(ca=>ca.CATEGORY_ID == category_id).CATEGORY_NAME;
                                string request_date = context.REQUEST_NEW.FirstOrDefault(ne => ne.REQUEST_ID == requestID).REQUEST_DATE.Value.ToString();
                                string sender = context.OWNERS.FirstOrDefault(o => o.EMPLOYEE_ID == context.REQUEST_NEW.FirstOrDefault(re => re.REQUEST_ID == requestID).EMPLOYEE_ID).EMPLOYEE_NAME;
                                string reason = context.REQUEST_NEW.FirstOrDefault(re => re.REQUEST_ID == requestID).REASON;
                                write_XML("New", requestID.ToString(), category_name, request_date, sender, reason, "");
                            }
                        }
                        if (input == "request liquidation")
                        {
                            //Get the Status of Asset is chosen
                            string assetID = _frmNotice.dataGridViewRequest.Rows[i].Cells[6].Value.ToString();
                            ASSET asset = context.ASSETs.FirstOrDefault(ass => ass.ASSET_ID == assetID);
                            //Using tempodary  EMPLOYEE_ID as asset STATUS
                            string asset_status = asset.EMPLOYEE_ID;
                            REQUEST_LIQUIDATION rL = context.REQUEST_LIQUIDATION.FirstOrDefault(r => r.REQUEST_ID == requestID);
                            CommonClassExecute<REQUEST_LIQUIDATION> cce = new CommonClassExecute<REQUEST_LIQUIDATION>(rL.REQ_STATUS, asset_status, input);
                            rL.REQ_STATUS = cce.execute_request(result);
                            //Update status_ID for asset
                            asset.EMPLOYEE_ID = cce.getASSET_STATUS();
                            if (_control == "Delete")
                            {
                                context.DeleteObject(rL);
                                _control = null;
                            }
                            if (rL.REQ_STATUS == "RE006")
                            {
                                string asset_id = context.REQUEST_LIQUIDATION.FirstOrDefault(ne => ne.REQUEST_ID == requestID).ASSET_ID;
                                string asset_name = context.ASSETs.FirstOrDefault(ca => ca.ASSET_ID == asset_id).ASSET_NAME;
                                string request_date = context.REQUEST_LIQUIDATION.FirstOrDefault(ne => ne.REQUEST_ID == requestID).REQUEST_DATE.Value.ToString();
                                string sender = context.OWNERS.FirstOrDefault(o => o.EMPLOYEE_ID == context.REQUEST_LIQUIDATION.FirstOrDefault(re => re.REQUEST_ID == requestID).EMPLOYEE_ID).EMPLOYEE_NAME;
                                string reason = context.REQUEST_LIQUIDATION.FirstOrDefault(re => re.REQUEST_ID == requestID).REASON;
                                write_XML("Liquidation", requestID.ToString(), asset_name, request_date, sender, reason, "");
                            }
                        }
                        if (input == "request maintenance")
                        {
                            //Get the Status of Asset is chosen
                            string assetID = _frmNotice.dataGridViewRequest.Rows[i].Cells[6].Value.ToString();
                            ASSET asset = context.ASSETs.FirstOrDefault(ass => ass.ASSET_ID == assetID);
                            //Using tempodary  EMPLOYEE_ID as asset STATUS
                            string asset_status = asset.EMPLOYEE_ID;
                            REQUEST_MAINTENANCE rM = context.REQUEST_MAINTENANCE.FirstOrDefault(r => r.REQUEST_ID == requestID);
                            CommonClassExecute<REQUEST_MAINTENANCE> cce = new CommonClassExecute<REQUEST_MAINTENANCE>(rM.REQ_STATUS, asset_status, input);
                            rM.REQ_STATUS = cce.execute_request(result);
                            //Update status_ID for asset
                            asset.EMPLOYEE_ID = cce.getASSET_STATUS();
                            if (_control == "Delete")
                            {
                                context.DeleteObject(rM);
                                _control = null;
                            }
                            if (rM.REQ_STATUS == "RE006")
                            {
                                string asset_id = context.REQUEST_MAINTENANCE.FirstOrDefault(ne => ne.REQUEST_ID == requestID).ASSET_ID;
                                string asset_name = context.ASSETs.FirstOrDefault(ca => ca.ASSET_ID == asset_id).ASSET_NAME;
                                string request_date = context.REQUEST_MAINTENANCE.FirstOrDefault(ne => ne.REQUEST_ID == requestID).STARTS_DATE.Value.ToString();
                                string sender = context.OWNERS.FirstOrDefault(o => o.EMPLOYEE_ID == context.REQUEST_MAINTENANCE.FirstOrDefault(re => re.REQUEST_ID == requestID).EMPLOYEE_ID).EMPLOYEE_NAME;
                                string reason = context.REQUEST_MAINTENANCE.FirstOrDefault(re => re.REQUEST_ID == requestID).REASON;
                                string return_date = context.REQUEST_MAINTENANCE.FirstOrDefault(ne => ne.REQUEST_ID == requestID).END_DATE.Value.ToString();
                                write_XML("Maintenance", requestID.ToString(), asset_name, request_date, sender, reason, return_date);
                            }
                        }
                        if (input == "request borrow")
                        {
                            REQUEST_BORROW rB = context.REQUEST_BORROW.FirstOrDefault(r => r.REQUEST_ID == requestID);
                            CommonClassExecute<REQUEST_BORROW> cce = new CommonClassExecute<REQUEST_BORROW>(rB.REQ_STATUS);
                            rB.REQ_STATUS = cce.execute_request(result);
                            if (_control == "Delete")
                            {
                                context.DeleteObject(rB);
                                _control = null;
                            }
                            if (rB.REQ_STATUS == "RE006")
                            {
                                string asset_id = context.REQUEST_BORROW.FirstOrDefault(ne => ne.REQUEST_ID == requestID).ASSET_ID;
                                string asset_name = context.ASSETs.FirstOrDefault(ca => ca.ASSET_ID == asset_id).ASSET_NAME;
                                string request_date = context.REQUEST_BORROW.FirstOrDefault(ne => ne.REQUEST_ID == requestID).REQUEST_DATE.Value.ToString();
                                string sender = context.OWNERS.FirstOrDefault(o => o.EMPLOYEE_ID == context.REQUEST_BORROW.FirstOrDefault(re => re.REQUEST_ID == requestID).EMPLOYEE_ID).EMPLOYEE_NAME;
                                string reason = context.REQUEST_BORROW.FirstOrDefault(re => re.REQUEST_ID == requestID).REASON;
                                write_XML("Borrow", requestID.ToString(), asset_name, request_date, sender, reason, "");
                            }
                        }
                    }
                }
            }

            //Save data into the database
            MessageBox.Show("Update successful!");
            context.SaveChanges();
            btnReload_Click();
        }

        public void btnClose_Click()
        {
            _frmNotice.Hide();
            _frmNotice.timerLoad.Start();
        }

        public void timerLoad_Tick()
        {
            load_data();
            string result = split_request(req_new.Count, req_liq.Count, req_mai.Count, req_bor.Count);
            if (result != null)
            {
                _frmNotice.timerLoad.Stop();
                _frmNotice.MAT_NotifyIcon.ShowBalloonTip(3000, "Notify", result, ToolTipIcon.Info);
                //Reset data for Requests (defend the ballon is shown)
                load_check_data();
            }
        }

        public void MAT_NotifyIcon_BalloonTipClicked()
        {
            MAT.Controllers.ctrNotice._frmNotice.ShowDialog();
        }

        public void MAT_NotifyIcon_MouseDoubleClick()
        {
            showNoticeToolStripMenuItem_Click();
        }

    }

    /// <summary>
    /// This is Template class to process data in 4 Request tables
    /// </summary>
    /// <typeparam name="T"></typeparam>
    class CommonClassExecute<T>
    {
        string REQ_STATUS;
        string ASSET_STATUS;
        string REQUEST_TYPE;

        ///Approve1: Admin 2 (Huey)      RE003
        ///Approve2: Admin 0 (Donald)    RE004

        public CommonClassExecute(string REQ_STATUS_temp)
        {
            this.REQ_STATUS = REQ_STATUS_temp;
            this.ASSET_STATUS = null;
            this.REQUEST_TYPE = null;
        }

        public CommonClassExecute(string REQ_STATUS_temp, string ASSET_STATUS_temp, string REQUEST_TYPE_temp)
        {
            this.REQ_STATUS = REQ_STATUS_temp;
            this.ASSET_STATUS = ASSET_STATUS_temp;
            this.REQUEST_TYPE = REQUEST_TYPE_temp;
        }

        public string getASSET_STATUS()
        {
            return ASSET_STATUS;
        }

        public void display_combobox(int row, DataGridView dGV, int priority, string empID)
        {
            //For User
            if (priority == 3)
            {
                if (REQ_STATUS == "RE001")
                {
                    if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Cancel"))
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Cancel");
                }
                else
                    if (REQ_STATUS == "RE002")
                    {
                        if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Deny"))
                            ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Deny");
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Value = "Deny";
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).ReadOnly = true;
                    }
                    else
                        if (REQ_STATUS == "RE005")
                        {
                            if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Cancel"))
                                ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Cancel");
                            ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Value = "Cancel";
                            ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).ReadOnly = true;
                        }
                        else
                            if (REQ_STATUS == "RE004")
                            {
                                if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Approve2"))
                                    ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Approve2");
                                ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Value = "Approve2";
                                ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).ReadOnly = true;
                            }
                            else
                                if (REQ_STATUS == "RE003")
                                {
                                    if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Approve1"))
                                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Approve1");
                                    ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Value = "Approve1";
                                    ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).ReadOnly = true;
                                }
                                else
                                {
                                    if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Done"))
                                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Done");
                                }
            }
            //For Admin 0
            if (priority == 0)
            {
                if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Approve"))
                    ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Approve");
                if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Deny"))
                    ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Deny");
                if (dGV.Rows[row].Cells[5].Value.ToString() == empID)
                {
                    if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Cancel"))
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Cancel");
                }
                if (REQ_STATUS == "RE005")
                    ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).ReadOnly = true;
                if (REQ_STATUS == "RE006")
                {
                    if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Done"))
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Done");
                }
            }
            //For Admin 1
            if (priority == 1)
            {
                if (REQ_STATUS == "RE004")
                {
                    if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Finish"))
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Finish");
                }
                if (dGV.Rows[row].Cells[5].Value.ToString() == empID)
                {
                    if (REQ_STATUS == "RE003")
                    {
                        if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Cancel"))
                            ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Cancel");
                    }
                    if (REQ_STATUS == "RE002")
                    {
                        if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Deny"))
                            ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Deny");
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Value = "Deny";
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).ReadOnly = true;
                    }
                    if (REQ_STATUS == "RE005")
                    {
                        if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Cancel"))
                            ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Cancel");
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Value = "Cancel";
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).ReadOnly = true;
                    }
                    if (REQ_STATUS == "RE006")
                    {
                        if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Done"))
                            ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Done");
                    }
                }
            }
            //For Admin 2
            if (priority == 2)
            {
                if (REQ_STATUS == "RE001")
                {
                    if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Approve"))
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Approve");
                    if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Deny"))
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Deny");
                }
                if (dGV.Rows[row].Cells[5].Value.ToString() == empID)
                {
                    if (REQ_STATUS == "RE001")
                    {
                        if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Cancel"))
                            ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Cancel");
                    }
                    if (REQ_STATUS == "RE002")
                    {
                        if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Deny"))
                            ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Deny");
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Value = "Deny";
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).ReadOnly = true;
                    }
                    if (REQ_STATUS == "RE003")
                    {
                        if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Approve1"))
                            ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Approve1");
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Value = "Approve1";
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).ReadOnly = true;
                    }
                    if (REQ_STATUS == "RE004")
                    {
                        if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Approve2"))
                            ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Approve2");
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Value = "Approve2";
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).ReadOnly = true;
                    }
                    if (REQ_STATUS == "RE005")
                    {
                        if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Cancel"))
                            ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Cancel");
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Value = "Cancel";
                        ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).ReadOnly = true;
                    }
                    if (REQ_STATUS == "RE006")
                    {
                        if (!((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Contains("Done"))
                            ((DataGridViewComboBoxCell)dGV.Rows[row].Cells[0]).Items.Add("Done");
                    }
                }
            }
        }

        public string execute_request(string result)
        {
            if (result == "Done" || result == "Cancel")
            {
                //Assume
                ctrNotice._control = "Delete";
            }
            if (result == "Deny")
            {
                REQ_STATUS = "RE002";
            }
            if (result == "Finish")
            {
                //Save data into XML file ====================> Haizzzzzzzzzzz
                REQ_STATUS = "RE006";
            }
            if (result == "Approve")
            {
                if (MAT.Controllers.ctrLogin.priority == 0)
                {
                    REQ_STATUS = "RE004";
                    if (REQUEST_TYPE == "request liquidation")
                        ASSET_STATUS = "Liquidation";
                    if (REQUEST_TYPE == "request maintenance")
                        ASSET_STATUS = "Maintenance";
                }
                if (MAT.Controllers.ctrLogin.priority == 2)
                {
                    REQ_STATUS = "RE003";
                }
            }
            return REQ_STATUS;
        }
    }
}
